import core from '@common/core'
import basic from '@common/basic';
const request = core.getExportResource('src/core/utils/http-tools.js').default;
const safeParseJSON =basic.getExportResource('src/basic/components/ty-select-object/utils/util.js')
console.log('二开')
export const createProps = () => ({
  field: {
    type: Object
  },
  // 自定义接口场景的参数
  customUrlParams: {
    type: Object,
    default: () => {
      return null;
    }
  }
});

export const createEmits = () => ['confirm'];

export const useSelectObjectContent = (props, emit) => {
  const { proxy } = getCurrentInstance();
  const gridOptions = reactive({
    loading: false,
    height: '450px',
    align: null,
    rowConfig: {
      height: 34,
      isHover: true,
      isCurrent: true
    },
    columnConfig: {
      resizable: true
    },
    scrollY: {
      enabled: true,
      gt: 10
    },
    showOverflow: true,
    showHeaderOverflow: true,
    data: []
  });
  const searchParams = reactive({
    pageInfo: {
      currentPage: 1,
      pageSize: 20,
      total: 0
    },
    queryConditions: {
      keyword: '',
      conditionGroups: null,
      conditionJoint: ''
    }
  });
  const searchBtnOptions = ref([
    { title: proxy.$t('basic.btn.cancel'), type: 'neutral', loading: false, key: 'cancel' },
    { title: proxy.$t('basic.btn.search'), loading: false, key: 'confirm' }
  ]);

  const isAdvancedSearch = computed(() => props.field?.options?.datasourceType === '1');

  // 从对象中取属性的值
  const getPropertyValue = (row, column, ibaDefOid) => {
    // IBA属性从对象中取值
    if (ibaDefOid) {
      return row.ibaAttrMapForSearch ? row.ibaAttrMapForSearch[column.field] || '' : '';
    }
    // 有真值时取真值, 有额外值时取额外值
    return row[column.field]
      ? row[column.field]
      : row.extAttrMapForSearch
        ? row.extAttrMapForSearch[column.field] || ''
        : '';
  };

  const columns = computed(() => {
    const arr =
      props.field.options.objectSelectData?.columns?.map(({ displayName, propertyName, fixed, width, ibaDefOid }) =>
        fixed
          ? {
              fixed: 'left',
              field: propertyName,
              title: displayName,
              width,
              formatter: ({ row, column }) => getPropertyValue(row, column, ibaDefOid)
            }
          : {
              field: propertyName,
              title: displayName,
              width,
              formatter: ({ row, column }) => getPropertyValue(row, column, ibaDefOid)
            }
      ) || [];
    if (props.field.type === 'data-table' || (props.field.options.isMultiple && arr)) {
      arr.unshift({ type: 'checkbox', width: 50, fixed: 'left' });
    }
    return arr;
  });

  const tableData = computed(() => {
    let list = gridOptions.data;
    if (!isAdvancedSearch.value && searchParams.queryConditions.keyword) {
      list = list.filter(
        item =>
          item.displayFullName?.includes(searchParams.queryConditions.keyword) ||
          item.objectNumber?.includes(searchParams.queryConditions.keyword) ||
          // modify by caoy 2025/02/27 增加个name的过滤搜索
          item.name?.toLowerCase().includes(searchParams.queryConditions.keyword.toLowerCase())
      );
    }
    return list;
  });

  const filterPoper = ref();
  const searchConditonRef = ref();
  const tableRef = ref();

  const selectRow = ref(null);

  const setCurRow = row => {
    selectRow.value = row;
  };

  const setPopover = isOpenPopover => filterPoper.value?.setVisible(isOpenPopover);

  const searchTable = () => {
    if (isAdvancedSearch.value) {
      getTableData();
    }
  };
  /**
   * @description 刷新新增独立的方法
   * @author caoy
   * @Date 2025-02-28 11:36:13
   */
  const refreshTableData = () => {
    // modify by caoy 2025/02/27 刷新时清空搜索关键字
    searchParams.queryConditions.keyword = '';
    getTableData();
  };
  const getCustomTableData = async () => {
    const { customParams } = props.field.options.objectSelectData || {};
    if (!customParams?.restfulUrl) return;
    gridOptions.loading = true;
    const res = await request({
      method: customParams?.requestType || 'POST',
      url: customParams.restfulUrl,
      data: safeParseJSON(props.customUrlParams || customParams?.urlParams)
    });
    if (res?.data?.success) {
      gridOptions.data = res.data.data?.list || [];
      searchParams.pageInfo.total = res.data.data?.total;
    }
    gridOptions.loading = false;
  };
  const getAdvancedTableData = async () => {
    gridOptions.loading = true;
    const { columns, contextList, typeList, viewCondition, conditionGroups, conditionJoint } =
      props.field.options.objectSelectData || {};
    const res = await request({
      method: 'POST',
      url: '/rest/v1/search/queryByConditionForPage',
      data: {
        columns,
        contextList,
        typeList,
        viewCondition,
        needCount: true,
        keyword: searchParams.queryConditions.keyword,
        pageNum: searchParams.pageInfo.currentPage,
        pageSize: searchParams.pageInfo.pageSize,
        // modify by caoy 2025/02/28 如果高级查询条件删除了 则使用默认得条件
        conditionGroups:
          searchParams.queryConditions.conditionGroups?.length > 0
            ? searchParams.queryConditions.conditionGroups
            : conditionGroups,
        conditionJoint: searchParams.queryConditions.conditionJoint || conditionJoint,
        ignoreWrk: true
      }
    });
    if (res?.data?.success) {
      gridOptions.data = res.data.data?.list || [];
      searchParams.pageInfo.total = res.data.data?.total;
    }
    gridOptions.loading = false;
  };
  const getTableData = () => {
    isAdvancedSearch.value ? getAdvancedTableData() : getCustomTableData();
  };
  // 操作处理
  const searchOperate = command => {
    if (command == 'confirm') {
      searchParams.queryConditions.conditionGroups = searchConditonRef.value?.getConditionParams();
      searchParams.queryConditions.conditionJoint = searchConditonRef.value?.allCondition;
      getAdvancedTableData();
    }
    setPopover(false);
  };

  // 将对象选择绑定的映射关系解析成对应值
  const transSpanToValue = (htmlString, row) => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlString, 'text/html');
    const spans = doc.querySelectorAll('span');
    spans.forEach(span => {
      // 获取span的父节点
      const parent = span.parentNode;
      const propsKey = span.getAttribute('value');
      // 将span的内容添加到父节点中，并移除span标签
      parent.replaceChild(document.createTextNode(`${row[propsKey] || ''}`), span);
    });
    return doc.body.innerText;
  };

  const confirmFunc = row => {
    if (row || (props.field.type !== 'data-table' && !props.field.options.isMultiple)) {
      emit('confirm', row || selectRow.value);
    } else {
      const attr = props.field.options.objectSelectData?.attrMap[0]?.attr;
      emit(
        'confirm',
        tableRef.value?.grid
          ?.getCheckboxRecords()
          .map(item => ({ ...item, widgetShowText: transSpanToValue(attr, item) }))
      );
    }
  };
  /**
   * @description 获取高级查询组件默认类型
   * @author caoy
   * @Date 2025-02-26 17:04:15
   */
  const getDefaultTypeList = computed(() => {
    let list = [];
    if (props.field.options.objectSelectData?.typeList?.length > 0) {
      list = props.field.options.objectSelectData?.typeList.map(item => {
        return item.typeOid;
      });
    }
    return list;
  });
  /**
   * @description 获取高级查询组件默认类型选项
   * @author caoy
   * @Date 2025-02-26 17:04:43
   */
  const getDefaultTypeOptions = computed(() => {
    let list = [];
    if (props.field.options.objectSelectData?.typeList?.length > 0) {
      list = props.field.options.objectSelectData?.typeList.map(item => {
        return {
          ...item,
          oid: item.typeOid,
          inthid: item.typeInthid
        };
      });
    }
    return list;
  });

  return {
    gridOptions,
    searchParams,
    searchBtnOptions,
    isAdvancedSearch,
    columns,
    tableData,
    filterPoper,
    searchConditonRef,
    tableRef,
    selectRow,
    setCurRow,
    setPopover,
    searchTable,
    getCustomTableData,
    getAdvancedTableData,
    getTableData,
    searchOperate,
    transSpanToValue,
    confirmFunc,
    getDefaultTypeList,
    getDefaultTypeOptions,
    refreshTableData
  };
};
